/*
 * @Author: muge
 * @Date: 2025-11-11 16:33:24
 * @LastEditors: muge
 * @LastEditTime: 2025-11-12 11:11:44
 */
// 调整整个页面布局的版本，包括 header 和 footer 都会受影响
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

interface UseMobileInputFullLayoutOptions {
  pageRef: Ref<HTMLDivElement | null>
  contentRef: Ref<HTMLDivElement | null>
  footerRef: Ref<HTMLDivElement | null>
  onFocus?: () => void
  onBlur?: () => void
  /** 延迟时间（毫秒），默认 300 */
  delay?: number
}

interface UseMobileInputFullLayoutReturn {
  handleFocus: () => void
  handleBlur: () => void
  /** 当前是否处于聚焦状态 */
  isFocused: Ref<boolean>
  /** 软键盘是否弹起（通过视口高度变化检测） */
  isKeyboardVisible: Ref<boolean>
}

export function useMobileInputFullLayout({
  pageRef,
  contentRef,
  footerRef,
  onFocus,
  onBlur,
  delay = 300
}: UseMobileInputFullLayoutOptions): UseMobileInputFullLayoutReturn {
  let savedScrollTop = 0
  const isFocused = ref(false)
  const isKeyboardVisible = ref(false)
  let originalContentPaddingBottom = ''
  let initialViewportHeight = 0

  // 检测软键盘是否弹起（通过视口高度变化）
  const checkKeyboardVisibility = () => {
    if (!window.visualViewport) {
      isKeyboardVisible.value = false
      return
    }

    const vpHeight = window.visualViewport.height
    const windowHeight = window.innerHeight

    // 如果视口高度明显小于窗口高度，说明软键盘弹起
    // 设置阈值 150px，避免误判
    const threshold = 150
    isKeyboardVisible.value = windowHeight - vpHeight > threshold
  }

  const updatePageHeight = () => {
    const vp = window.visualViewport
    if (!vp || !pageRef.value) return
    
    const height = vp.height
    // 同时更新 html、body、#app 和 page 的高度，避免出现白底
    document.documentElement.style.height = `${height}px`
    document.body.style.height = `${height}px`
    const appEl = document.getElementById('app')
    if (appEl) {
      appEl.style.height = `${height}px`
    }
    pageRef.value.style.height = `${height}px`
  }

  const handleFocus = () => {
    if (isFocused.value) return // 防止重复触发
    isFocused.value = true
    savedScrollTop = contentRef.value?.scrollTop ?? 0
    
    // 🔥 关键：先更新页面高度，让 footer 先定位到键盘上方
    updatePageHeight()
    
    // 给 content 添加 padding-bottom，避免内容被 footer 遮住
    if (footerRef.value && contentRef.value) {
      const footerHeight = footerRef.value.getBoundingClientRect().height
      originalContentPaddingBottom = contentRef.value.style.paddingBottom || ''
      contentRef.value.style.paddingBottom = `${footerHeight}px`
    }
    
    // 等待布局调整完成后再滚动和禁用滚动
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        // 在下一帧滚动到顶部
        window.scrollTo(0, 0)
        document.documentElement.scrollTop = 0
        document.body.scrollTop = 0
        onFocus?.()
      })
    })
  }

  const handleBlur = () => {
    if (!isFocused.value) return // 防止重复触发
    isFocused.value = false
    
    // 立即恢复所有元素的高度，避免出现白底和闪烁
    const restoreHeight = () => {
      const fullHeight = window.innerHeight || window.visualViewport?.height || '100dvh'
      document.documentElement.style.height = `${fullHeight}px`
      document.body.style.height = `${fullHeight}px`
      const appEl = document.getElementById('app')
      if (appEl) {
        appEl.style.height = `${fullHeight}px`
      }
      if (pageRef.value) {
        pageRef.value.style.height = '100dvh'
      }
    }
    
    // 立即恢复高度
    restoreHeight()
    
    // 恢复 content 的 padding-bottom
    if (contentRef.value) {
      if (originalContentPaddingBottom) {
        contentRef.value.style.paddingBottom = originalContentPaddingBottom
      } else {
        contentRef.value.style.removeProperty('padding-bottom')
      }
    }
    
    // 调用失焦回调
    onBlur?.()

    // 使用 requestAnimationFrame 更及时地恢复，减少闪烁
    requestAnimationFrame(() => {
      // 再次确保高度正确
      restoreHeight()
      
      // 恢复 content 滚动位置（立即恢复，不等键盘完全收起）
      if (contentRef.value) {
        contentRef.value.scrollTop = savedScrollTop
      }
      
      // 延迟一点再确保一次，等键盘完全收起
      setTimeout(() => {
        restoreHeight()
        // 再次确保 body/html 没有滚动条
        document.documentElement.scrollTop = 0
        document.body.scrollTop = 0
        window.scrollTo(0, 0)
      }, 100) // 减少延迟到 100ms
    })
  }


  const handleViewportResize = () => {
    // 检测软键盘状态
    checkKeyboardVisibility()
    // 仅在聚焦状态下响应 visualViewport 变化
    if (isFocused.value) {
      updatePageHeight()
    }
  }

  onMounted(() => {
    if (pageRef.value) {
      pageRef.value.style.height = '100dvh'
    }
    if (window.visualViewport) {
      initialViewportHeight = window.visualViewport.height
      window.visualViewport.addEventListener('resize', handleViewportResize)
    }
    // 初始检测一次
    checkKeyboardVisibility()
  })

  onUnmounted(() => {
    if (window.visualViewport) {
      window.visualViewport.removeEventListener('resize', handleViewportResize)
    }
  })

  return {
    handleFocus,
    handleBlur,
    /** 当前是否处于聚焦状态 */
    isFocused,
    /** 软键盘是否弹起（通过视口高度变化检测） */
    isKeyboardVisible
  }
}

